﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TS.Bussiness;
using TS.Commons;
using TS.Entities;
using Wuqi.Webdiyer;

namespace Tranco.Views
{
    public partial class ScheduleManagement : System.Web.UI.Page
    {
        private int _pageSize; // Number record display on gridview
        private int _pageIndex; // Number page display
        private string _filter; // Condition filter 
        private string _orderBy; // Condition order follow header on gridview
        private string _status;
        protected void Page_Load(object sender, EventArgs e)
        {
            _pageIndex = 1;
            _pageSize = 10;
            _status = drStatus.SelectedItem.Value.ToStringOrDefault();
            if (drStatus.SelectedItem.Value == " ")
                _status = @"Đang đi' or s.Status = N'Chưa đi' or s.Status is null or s.Status = N'Đang về";
            if (!IsPostBack)
            {
                HiddenFieldYear.Value = Request.QueryString["year"].ToStringOrDefault();
                HiddenFieldDay.Value = Request.QueryString["day"].ToStringOrDefault();
                HiddenFieldWeek.Value = Request.QueryString["week"].ToStringOrDefault();
                HiddenFieldMonth.Value = Request.QueryString["month"].ToStringOrDefault();
                HiddenFieldSearch.Value = Request.QueryString["str"].ToStringOrDefault();


              

                if (string.IsNullOrEmpty(HiddenFieldYear.Value))
                    drYear.Items.FindByValue(DateTime.Today.Year.ToStringOrDefault()).Selected = true;
                else
                {
                    drYear.Items.FindByValue(HiddenFieldYear.Value.ToStringOrDefault()).Selected = true;
                }

                if (string.IsNullOrEmpty(HiddenFieldMonth.Value.ToStringOrDefault()))
                    drMonth.Items.FindByValue(DateTime.Today.Month.ToStringOrDefault()).Selected = true;
                else
                {
                    drMonth.Items.FindByValue(HiddenFieldMonth.Value.ToStringOrDefault()).Selected = true;
                }

                drWeek.Items.FindByValue(HiddenFieldWeek.Value.ToStringOrDefault()).Selected = true;
                drDay.Items.FindByValue(HiddenFieldDay.Value.ToStringOrDefault()).Selected = true;
                txtFindUser.Text = HiddenFieldSearch.Value.ToStringOrDefault();

                _orderBy = HiddenFieldOrderBy.Value.ToStringOrDefault();
                _filter = HiddenFieldSearch.Value.ToStringOrDefault();
                BindData(_pageSize, _pageIndex, _filter, "StartDate DESC",
                    drYear.SelectedItem.Value.ToStringOrDefault(),
                                                                drMonth.SelectedItem.Value.ToStringOrDefault(),
                                                                HiddenFieldWeek.Value.ToStringOrDefault(), HiddenFieldDay.Value.ToStringOrDefault()
                    );

            }

        }

        /// <summary>
        /// Bind Data
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="filter"></param>
        /// <param name="orderBy"></param>
        private void BindData(int pageSize, int pageIndex, string filter, string orderBy, string year, string month,
                            string week, string day)
        {
            int totalRecord;
            var bussiness = new ScheduleBussiness();
            Collection<Schedule> collection = bussiness.ReadSchedulePaged(pageSize, pageIndex, filter, orderBy,
                                                                year, month, week, day, "", _status,
                                                            out totalRecord);
            if (collection != null)
                if (collection.Count == 0)
                {
                    Schedule obj = new Schedule();
                    obj.StartDateS = "No Data";
                    collection.Add(obj);
                }
            GridViewList.DataSource = collection;
            GridViewList.DataBind();
            AspNetPager.RecordCount = totalRecord;
            AspNetPager.PageSize = pageSize;
        }

        /// <summary>
        /// Page Changing
        /// </summary>
        /// <param name="src"></param>
        /// <param name="e"></param>
        protected void AspNetPagerPageChanging(object src, PageChangingEventArgs e)
        {
            _pageIndex = e.NewPageIndex;
            _orderBy = HiddenFieldOrderBy.Value;
            if (!string.IsNullOrEmpty(_orderBy))
            {
                _orderBy = _orderBy + HiddenFieldStatusOrder.Value;
            }
            _filter = HiddenFieldStringFilter.Value;
            BindData(_pageSize, _pageIndex, _filter, _orderBy, drYear.SelectedItem.Value.ToStringOrDefault(),
                drMonth.SelectedItem.Value.ToStringOrDefault(), drWeek.SelectedItem.Value.ToStringOrDefault(), drDay.SelectedItem.Value.ToStringOrDefault()
                );
        }

        /// <summary>
        /// FilterData
        /// </summary>
        protected void DataFilter()
        {
            //get filter
            _filter = HiddenFieldStringFilter.Value;
            //get orderby
            _orderBy = HiddenFieldOrderBy.Value;

            if (!string.IsNullOrEmpty(_orderBy))
            {
                _orderBy = _orderBy + HiddenFieldStatusOrder.Value;
            }
            //set property of page
            _pageIndex = 1;
            AspNetPager.CurrentPageIndex = _pageIndex;
            //load data
            BindData(_pageSize, _pageIndex, _filter, _orderBy, drYear.SelectedItem.Value.ToStringOrDefault(),
                drMonth.SelectedItem.Value.ToStringOrDefault(), drWeek.SelectedItem.Value.ToStringOrDefault(), drDay.SelectedItem.Value.ToStringOrDefault()
                );
        }

        protected void GridViewListSorting(object sender, GridViewSortEventArgs e)
        {
            HiddenFieldOrderBy.Value = e.SortExpression;
            HiddenFieldStatusOrder.Value = HiddenFieldStatusOrder.Value.Equals(" ASC ") ? " DESC " : " ASC ";

            DataFilter();
        }

        private string UrlUpdate = "~/Views/UpdateSchedule.aspx?sid=";
        private string UrlUpdateOwner = "~/Views/UpdateOwner.aspx?ownerid=";
        private string UrlUpdateGateway = "~/Views/UpdateGateway.aspx?gwid=";
        private string UrlUpdateNumber = "~/Views/UpdateNumberBike.aspx?nbid=";

        /// <summary>
        /// GridViewListRowCommand
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewListRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Owner")
            {
                var result = e.CommandArgument.ToNumeric();
                if (result > 0)
                {
                    Response.Redirect(UrlUpdateOwner + result);

                }

            }
            else
                if (e.CommandName == "Gateway")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdateGateway + result);
                    }

                }
                else if (e.CommandName == "NumberBike")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdateNumber + result);
                    }

                }
                else if (e.CommandName == "Schedule")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdate + result + "&day=" + drDay.SelectedItem.Value.ToStringOrDefault() + "&week=" + drWeek.SelectedItem.Value.ToStringOrDefault()
                                                                    + "&month=" + drMonth.SelectedItem.Value.ToStringOrDefault()
                                                                    + "&year=" + drYear.SelectedItem.Value.ToStringOrDefault()
                                                                    + "&str=" + txtFindUser.Text.ToStringOrDefault()
                                                                    );
                    }

                }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            HiddenFieldStringFilter.Value = txtFindUser.Text;

            DataFilter();
        }

        protected void btnEnter_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridViewList.Rows)
            {
                var cbSelection = (CheckBox)row.FindControl("cbSelection");
                if (cbSelection.Checked)
                {
                    var obj = new Schedule();
                    var linkButton = (LinkButton)row.FindControl("lbtContent");
                    obj.ScheduleId = linkButton.CommandArgument.ToNumeric();

                    var txt = (Label)row.FindControl("LabelStatus");

                    if (txt.Text == "Hoàn thành")
                    {
                        ClientAlert("Không thể xóa lịch trình đang ở trạng thái hoàn thành: " + linkButton.Text + "");
                        return;
                    }

                    var ub = new ScheduleBussiness();
                    if (ub.DeleteSchedule(obj) > 0)
                    {
                        ClientConfirm();
                    }
                    else
                    {
                        ClientAlert("Có lỗi xảy ra. Vui lòng kiểm tra lại.");
                    }
                }
            }
        }

        /// <summary>
        /// Message alert
        /// </summary>
        /// <param name="strAlert"></param>
        public void ClientAlert(string strAlert)
        {
            var strScript = new StringBuilder();
            strScript.Append("<script language=JavaScript>");
            string scriptString = string.Format(CultureInfo.CurrentCulture, @"window.alert('" + strAlert + "');</script> ");
            strScript.Append(scriptString);
            ClientScript.RegisterStartupScript(GetType(), "Pop", strScript.ToString());
        }

        /// <summary>
        /// Message confirm
        /// </summary>
        public void ClientConfirm()
        {
            var strScript = new StringBuilder();
            strScript.Append("<script language=JavaScript>");
            string scriptString = string.Format(CultureInfo.CurrentCulture, @"var result = window.confirm('Xóa thành công. Bạn có muốn load lại trang?'); " +
                     "if(result) location.href='/Views/ScheduleManagement.aspx';</script>");
            strScript.Append(scriptString);
            ClientScript.RegisterStartupScript(GetType(), "Pop", strScript.ToString());
        }

        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {

        }

        private void ExportExcel(int pageSize, int pageIndex, string filter, string orderBy, string year, string month,
                            string week, string day)
        {
            int totalRecord;
            var bussiness = new ScheduleBussiness();
            Collection<Schedule> collection = bussiness.ReadSchedulePaged(pageSize, pageIndex, filter, orderBy,
                                                                year, month, week, day, "", drStatus.SelectedItem.Value.ToStringOrDefault(),
                                                            out totalRecord);

            DataTable dtEmp = ToDataTable(collection);
            GridView gr = new GridView();
            gr.DataSource = dtEmp;
            gr.DataBind();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=LichTrinh.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (var sw = new StringWriter())
            {
                var hw = new HtmlTextWriter(sw);

                gr.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in gr.HeaderRow.Cells)
                {
                    cell.BackColor = gr.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in gr.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = gr.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = gr.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                gr.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }


            //string attachment = "attachment; filename=" + "EportToExcel.xls";
            //Response.ClearContent();
            //Response.AddHeader("content-disposition", attachment);
            //Response.ContentType = "application/vnd.ms-excel";
            //string tab = string.Empty;
            //foreach (DataColumn dtcol in dtEmp.Columns)
            //{
            //    Response.Write(tab + dtcol.ColumnName);
            //    tab = "\t";
            //}
            //Response.Write("\n");
            //foreach (DataRow dr in dtEmp.Rows)
            //{
            //    tab = "";
            //    for (int j = 0; j < dtEmp.Columns.Count; j++)
            //    {
            //        Response.Write(tab + Convert.ToString(dr[j]));
            //        tab = "\t";
            //    }
            //    Response.Write("\n");
            //}
            //Response.End();

        }

        private DataTable ToDataTable(Collection<Schedule> data)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Chủ hàng", typeof(string));
            table.Columns.Add("Cửa khẩu", typeof(string));
            table.Columns.Add("Số xe", typeof(string));
            table.Columns.Add("Số Cont", typeof(string));
            table.Columns.Add("Ngày đi", typeof(string));
            table.Columns.Add("Ngày về", typeof(string));
            table.Columns.Add("Chi Tiết", typeof(string));
            table.Columns.Add("Tình Trạng", typeof(string));



            foreach (var item in data)
            {
                DataRow row = table.NewRow();
                row[0] = item.OwnerName;
                row[1] = item.GateWayName;
                row[2] = item.NumberPlate;
                row[3] = item.NumberCont;
                row[4] = item.StartDateS;
                row[5] = item.EndDateS;
                row[6] = item.Content;
                row[7] = item.Status;

                table.Rows.Add(row);
            }
                DataRow row1 = table.NewRow();
                row1[0] = "";
                row1[1] = "";
                row1[2] = "";
                row1[3] = "";
                row1[4] = "";
                row1[5] = "";
                row1[6] = "";
                row1[7] = "";
                table.Rows.Add(row1);


                DataRow row2 = table.NewRow();
                row2[0] = "";
                row2[1] = "";
                row2[2] = "";
                row2[3] = "";
                row2[4] = "";
                row2[5] = "";
                row2[6] = "";
                row2[7] = "";
                table.Rows.Add(row2);

                DataRow row3 = table.NewRow();
                row3[0] = "";
                row3[1] = "";
                row3[2] = "";
                row3[3] = "";
                row3[4] = "";
                row3[5] = "";
                row3[6] = "";
                row3[7] = "";
                table.Rows.Add(row3);
            return table;
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {



            #region

            //get filter
            _filter = HiddenFieldStringFilter.Value;
            //get orderby
            _orderBy = HiddenFieldOrderBy.Value;

            if (!string.IsNullOrEmpty(_orderBy))
            {
                _orderBy = _orderBy + HiddenFieldStatusOrder.Value;
            }
            //set property of page
            _pageIndex = AspNetPager.CurrentPageIndex;
            //load data
            ExportExcel(_pageSize, _pageIndex, _filter, _orderBy, drYear.SelectedItem.Value.ToStringOrDefault(),
                        drMonth.SelectedItem.Value.ToStringOrDefault(), drWeek.SelectedItem.Value.ToStringOrDefault(),
                        drDay.SelectedItem.Value.ToStringOrDefault()
                );

            #endregion

            //#region

            //Response.Clear();
            //Response.Buffer = true;
            //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            //Response.Charset = "";
            //Response.ContentType = "application/vnd.ms-excel";
            //using (var sw = new StringWriter())
            //{
            //    var hw = new HtmlTextWriter(sw);

            //    GridViewList.HeaderRow.BackColor = Color.White;
            //    foreach (TableCell cell in GridViewList.HeaderRow.Cells)
            //    {
            //        cell.BackColor = GridViewList.HeaderStyle.BackColor;
            //    }
            //    foreach (GridViewRow row in GridViewList.Rows)
            //    {
            //        row.BackColor = Color.White;
            //        foreach (TableCell cell in row.Cells)
            //        {
            //            if (row.RowIndex % 2 == 0)
            //            {
            //                cell.BackColor = GridViewList.AlternatingRowStyle.BackColor;
            //            }
            //            else
            //            {
            //                cell.BackColor = GridViewList.RowStyle.BackColor;
            //            }
            //            cell.CssClass = "textmode";
            //        }
            //    }

            //    GridViewList.RenderControl(hw);

            //    //style to format numbers to string
            //    string style = @"<style> .textmode { } </style>";
            //    Response.Write(style);
            //    Response.Output.Write(sw.ToString());
            //    Response.Flush();
            //    Response.End();
            //}

            //#endregion

        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
}